package com.by.yz.mypersonal;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.by.yz.R;
import com.by.yz.Register.DoctorREST;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.entity.Department;
import com.by.yz.entity.Doctorbean;
import com.by.yz.entity.Hospital;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.DepartmentRESTFul;
import com.by.yz.loginUtil.HospitalRESTFul;
import com.by.yz.util.ToJSonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by mrs yang on 2017/1/17.
 */
public class PersonalRestDoctor extends BaseActivity implements View.OnClickListener{
    private EditText name,country,school,age,resume,position;
    private Button next;
    private String Name,School,Resume,Country,Position;
    private Hospital Hosp = new Hospital();
    private Department Depart = new Department();
    private Integer Age;
    private UserTest userTest;
    private Doctorbean getdt;
    private Spinner Hospital = null,Departm = null;
    private ArrayAdapter<CharSequence> adapterHospital = null;
    private ArrayAdapter<CharSequence> adapterDepartment = null;
    private static List<String> hospitalList = new ArrayList<String>();
    private static String[] hospitalInfo = new String[]{};
    private static List<String> hospitalId =new ArrayList<String>();
    private static List<String> departmentList = new ArrayList<String>();
    private static String[] departmentInfo = new String[]{};
    private static List<String> departmentId =new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_apply_doctor);
        setToolbarTitle("修改医生信息");
        userTest=(UserTest)getIntent().getSerializableExtra("resetdoctor");
        initView();
    }

    private void initView() {

        name=(EditText) findViewById(R.id.name);
        country=(EditText) findViewById(R.id.country);
        school=(EditText) findViewById(R.id.school);
        age=(EditText) findViewById(R.id.work);
        resume=(EditText) findViewById(R.id.DocterResume);
        position=(EditText)findViewById(R.id.position);
        next = (Button) findViewById(R.id.next);
        next.setOnClickListener(this);
        Hospital = (Spinner) super.findViewById(R.id.my_ho);
        Departm = (Spinner) super.findViewById(R.id.my_depart);

        HospitalRESTFul hospitalREST=new HospitalRESTFul();
        hospitalREST.getAllHospitals(new HospitalRESTFul.MyGETCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                hospitalList.clear();
                hospitalId.clear();
                hospitalList.add(0,"---请选择您工作的医院---");
                for (int i = 0; i < response.length(); i++) {
                    com.by.yz.entity.Hospital hospital;
                    JSONObject jsonObject = response.getJSONObject(i);
                    hospital = ToJSonObject.jsonToBean(jsonObject.toString(), Hospital.class);
                    hospitalList.add(i+1,hospital.getHospital());
                    hospitalId.add(i,hospital.getId()+"");
                }
                hospitalInfo = hospitalList.toArray(new String[hospitalList.size()]);
                handler.sendEmptyMessage(1);
            }
            @Override
            public void error(String error) {
                Log.e("error",error);
            }
        });

        DepartmentRESTFul DepartmentREST=new DepartmentRESTFul();
        DepartmentREST.getAllDepartments(new DepartmentRESTFul.MyGETCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                departmentList.clear();
                departmentId.clear();
                departmentList.add(0,"---请选择您的科室---");
                for (int i = 0; i < response.length(); i++) {
                    com.by.yz.entity.Department department;
                    JSONObject jsonObject = response.getJSONObject(i);
                    department = ToJSonObject.jsonToBean(jsonObject.toString(), Department.class);
                    departmentList.add(i+1,department.getDepartment());
                    departmentId.add(i,department.getId()+"");
                }
                departmentInfo = departmentList.toArray(new String[departmentList.size()]);
                handler.sendEmptyMessage(2);
            }
            @Override
            public void error(String error) {
                Log.e("error2",error);
            }
        });


    }
    protected Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    initDatas();
                    break;
                case 1:
                    initDatas1();
                    break;
                case 2:
                    initDatas2();
                    break;
                default:
                    break;
            }
        }
    };

    private void initDatas1() {
        this.adapterHospital = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_dropdown_item,hospitalInfo);
        this.Hospital.setAdapter(adapterHospital);
    }

    private void initDatas2() {
        this.adapterDepartment = new ArrayAdapter<CharSequence>(this,
                android.R.layout.simple_spinner_dropdown_item,departmentInfo);
        this.Departm.setAdapter(adapterDepartment);
        handler.sendEmptyMessage(0);
    }

    private  void initDatas(){
        DoctorREST doctorREST=new DoctorREST();
        doctorREST.getDoctorRESTo(new DoctorREST.MyGetCallBack() {
            @Override
            public void ok(JSONArray response) throws JSONException {
                for (int i=0;i<response.length();i++){
                    JSONObject jsonObject= response.getJSONObject(i);
                    getdt= ToJSonObject.jsonToBean(jsonObject.toString(),Doctorbean.class);
                    if(getdt.getLogin().equals(userTest.getPhonenumber())){
                        country.setText(getdt.getCountry());
                        name.setText(getdt.getDoctorname());
                        int j= adapterHospital.getCount();
                        for(i=0;i<j;i++){
                            if(getdt.getTextHospital().getHospital().equals(adapterHospital.getItem(i).toString())){
                                Hospital.setSelection(i,true);// 默认选中项
                                break;
                            }
                        }
                        int k= adapterDepartment.getCount();
                        for(i=0;i<k;i++){
                            if(getdt.getDepartment().getDepartment().equals(adapterDepartment.getItem(i).toString())){
                                Departm.setSelection(i,true);// 默认选中项
                                break;
                            }
                        }
                        position.setText(getdt.getPosition());
                        school.setText(getdt.getSchool());
                        age.setText(String.valueOf(getdt.getWorkingyears()));
                        resume.setText(getdt.getResume());
                        break;
                    }
                }
            }
            @Override
            public void error(String error) {
                Log.e("DoctorTestREST-error",error);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.next:
                String message = "";
                if(country.getText().toString().equals("")){
                    message="请输入您的籍贯";
                }else if(name.getText().toString().equals("")){
                    message="请输入您的真实姓名";
                }else if(Hospital.getSelectedItem().toString().equals("---请选择您工作的医院---")){
                    message="请选择您工作的医院";
                }else if(Departm.getSelectedItem().toString().equals("---请选择您的科室---")){
                    message = "请选择您的科室";
                }else if(position.getText().toString().equals("")){
                    message="请输入您的职位";
                }else if(school.getText().toString().equals("")){
                    message="请输入您毕业的学校全称";
                }else if(age.getText().toString().equals("")){
                    message="请输入您的工作年限";
                }else if(resume.getText().toString().equals("") ){
                    message="请输入您的个人简历";
                }
                if(!message.equals("")){
                    final MaterialDialog registerSuccess = new MaterialDialog.Builder(PersonalRestDoctor.this)
                            .content(message)
                            .show();
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        public void run() {
                            registerSuccess.dismiss();
                        }
                    }, 1000);
                }else {
                    Name=name.getText().toString();
                    Hosp.setHospital(Hospital.getSelectedItem().toString());
                    Hosp.setId(Integer.parseInt(hospitalId.get((int)(Hospital.getSelectedItemId())-1)));
                    School=school.getText().toString();
                    Age=Integer.valueOf(age.getText().toString());
                    Resume=resume.getText().toString();
                    Country=country.getText().toString();
                    Position=position.getText().toString();
                    Depart.setDepartment(Departm.getSelectedItem().toString());
                    Depart.setId(Integer.parseInt(departmentId.get((int)(Departm.getSelectedItemId())-1)));

                            DoctorREST doctorREST=new DoctorREST();
                            doctorREST.getDoctorRESTo(new DoctorREST.MyGetCallBack() {
                                @Override
                                public void ok(JSONArray response) throws JSONException {
                                    for (int i=0;i<response.length();i++){
                                        JSONObject jsonObject= response.getJSONObject(i);
                                        getdt= ToJSonObject.jsonToBean(jsonObject.toString(),Doctorbean.class);
                                        if(getdt.getLogin().equals(userTest.getPhonenumber())){
                                            Doctorbean doctorbean=new Doctorbean();
                                            Integer j=getdt.getId();
                                            doctorbean.setId(j);
                                            doctorbean.setCountry(Country);
                                            doctorbean.setDepartment(Depart);
                                            doctorbean.setDoctorname(Name);
                                            doctorbean.setFlag(getdt.getFlag());
                                            doctorbean.setLogin(getdt.getLogin());
                                            doctorbean.setPosition(Position);
                                            try {
                                                doctorbean.setmImageView(userTest.getHeadimg());

                                            }
                                            catch (Exception e){
                                                doctorbean.setmImageView("");
                                            }
                                            doctorbean.setResume(Resume);
                                            doctorbean.setSchool(School);
                                            doctorbean.setTextHospital(Hosp);
                                            doctorbean.setWorkingyears(Age);
                                            JSONObject data = ToJSonObject.beanToJSONObejct(doctorbean);
                                            DoctorREST doctor=new DoctorREST();
                                            doctor.putDoctorREST(data, new DoctorREST.MyPostCallBack() {
                                                @Override
                                                public void ok(JSONObject response) throws JSONException {
                                                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                                                    PersonalRestDoctor.this.finish();
                                                }
                                                @Override
                                                public void error(String error) {
                                                    Toast.makeText(getApplicationContext(), "提交格式不对,请重新填写信息", Toast.LENGTH_SHORT).show();
                                                    Log.e("DoctorTestREST-error",error);
                                                }
                                            });
                                            break;
                                        }
                                    }
                                }
                                @Override
                                public void error(String error) {
                                    Log.e("DoctorTestREST-error",error);
                                }
                            });

                }
                break;
        }
    }
}
